<template>
  <ComponentContainerProperty v-model="formData.style">
    <template #default>
      <el-form :model="formData" label-width="80px" class="compact-form">
        <!-- 基本配置 -->
        <el-form-item class="section-header">
          <div class="section-title">基本配置</div>
        </el-form-item>
        <el-card shadow="never" class="config-card">
          <div class="config-section">
            <div class="section-label">标题设置</div>
            <el-form-item label="区块标题" prop="sectionTitle" class="full-width-item">
              <el-input 
                v-model="formData.sectionTitle" 
                placeholder="请输入区块标题"
                size="small"
                clearable
              />
            </el-form-item>
            <el-form-item label="区块副标题" prop="sectionSubtitle" class="full-width-item">
              <el-input 
                v-model="formData.sectionSubtitle" 
                placeholder="请输入区块副标题（可选）"
                size="small"
                clearable
              />
            </el-form-item>
          </div>
          
          <div class="config-section">
            <div class="section-label">布局设置</div>
            <el-form-item label="布局类型" prop="layoutType" class="full-width-item">
              <el-radio-group v-model="formData.layoutType" size="small">
                <el-radio value="grid">网格布局</el-radio>
                <el-radio value="list">列表布局</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="更多链接" prop="moreUrl" class="full-width-item">
              <el-input 
                v-model="formData.moreUrl" 
                placeholder="请输入更多链接（可选）"
                size="small"
                clearable
              />
            </el-form-item>
          </div>
        </el-card>
        
        <!-- 精选项目列表 -->
        <el-form-item class="section-header">
          <div class="section-title">精选项目</div>
        </el-form-item>
        <el-card shadow="never" class="items-config-card">
          <div v-for="(item, index) in formData.featuredItems" :key="item.id" class="item-config">
            <div class="item-header">
              <span class="item-title">项目 {{ index + 1 }}</span>
              <div class="item-actions">
                <el-button 
                  type="danger" 
                  size="small" 
                  @click="removeItem(index)"
                  :disabled="formData.featuredItems.length <= 1"
                >
                  删除
                </el-button>
                <el-button 
                  v-if="index > 0"
                  type="primary" 
                  size="small" 
                  @click="moveItemUp(index)"
                >
                  上移
                </el-button>
                <el-button 
                  v-if="index < formData.featuredItems.length - 1"
                  type="primary" 
                  size="small" 
                  @click="moveItemDown(index)"
                >
                  下移
                </el-button>
              </div>
            </div>
            
            <div class="config-section">
              <div class="section-label">基本信息</div>
              <el-form-item 
                label="内容类型" 
                :prop="`featuredItems.${index}.contentType`" 
                class="full-width-item"
                :rules="[{ required: true, message: '请选择内容类型', trigger: 'change' }]"
              >
                <el-radio-group v-model="formData.featuredItems[index].contentType" size="small" @change="onContentTypeChange(index)">
                  <el-radio value="ad">广告</el-radio>
                  <el-radio value="text">文本</el-radio>
                </el-radio-group>
              </el-form-item>
            </div>
            
            <div class="config-section">
              <div class="section-label">图片配置</div>
              <el-form-item label="项目图片" :prop="`featuredItems.${index}.imgUrl`" class="compact-item">
                <UploadImg 
                  v-model="formData.featuredItems[index].imgUrl" 
                  :limit="1"
                >
                  <template #tip>400x300px</template>
                </UploadImg>
              </el-form-item>
            </div>
            
            <div class="config-section">
              <div class="section-label">内容配置</div>
              <el-form-item label="标题" :prop="`featuredItems.${index}.title`" class="full-width-item">
                <el-input 
                  v-model="formData.featuredItems[index].title" 
                  type="textarea"
                  :rows="2"
                  placeholder="请输入项目标题（支持换行）"
                  size="small"
                  resize="none"
                />
              </el-form-item>
              <el-form-item label="副标题" :prop="`featuredItems.${index}.subtitle`" class="full-width-item">
                <el-input 
                  v-model="formData.featuredItems[index].subtitle" 
                  placeholder="请输入项目副标题（可选）"
                  size="small"
                />
              </el-form-item>
              <!-- 广告类型显示价格字段 -->
              <el-form-item 
                v-if="formData.featuredItems[index].contentType === 'ad'" 
                label="价格" 
                :prop="`featuredItems.${index}.price`" 
                class="full-width-item"
              >
                <el-input 
                  v-model="formData.featuredItems[index].price" 
                  placeholder="请输入价格（可选）"
                  size="small"
                />
              </el-form-item>
              <!-- 文本类型显示富文本编辑器按钮 -->
              <el-form-item 
                v-if="formData.featuredItems[index].contentType === 'text'" 
                label="富文本" 
                :prop="`featuredItems.${index}.richText`" 
                class="full-width-item"
                :rules="[{ required: true, message: '请输入富文本内容', trigger: 'blur' }]"
              >
                <div class="rich-text-button-container">
                  <el-button 
                    type="primary" 
                    size="small" 
                    @click="openRichTextDialog(index)"
                    :icon="formData.featuredItems[index].richText ? 'ep:edit' : 'ep:plus'"
                  >
                    {{ formData.featuredItems[index].richText ? '编辑富文本内容' : '添加富文本内容' }}
                  </el-button>
                  <div v-if="formData.featuredItems[index].richText" class="rich-text-preview" v-html="getRichTextPreview(formData.featuredItems[index].richText)"></div>
                </div>
                <!-- 隐藏的输入框用于表单验证 -->
                <el-input 
                  v-model="formData.featuredItems[index].richText" 
                  style="display: none;"
                />
              </el-form-item>
              <el-form-item label="跳转链接" :prop="`featuredItems.${index}.url`" class="full-width-item">
                <el-input 
                  v-model="formData.featuredItems[index].url" 
                  placeholder="请输入跳转链接"
                  size="small"
                />
              </el-form-item>
            </div>
          </div>
          <el-button type="primary" size="small" @click="addItem">添加项目</el-button>
        </el-card>
      </el-form>
    </template>
  </ComponentContainerProperty>
  
  <!-- 富文本编辑弹窗 -->
  <el-dialog 
    v-model="richTextDialogVisible"
    title="编辑富文本内容"
    width="80%"
    :before-close="handleRichTextDialogClose"
    append-to-body
  >
    <div class="rich-text-dialog-content">
      <Editor 
        v-model="currentRichText"
        :height="400"
        :editorId="`featured-rich-text-editor`"
        placeholder="请输入富文本内容"
      />
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancelRichTextEdit">取消</el-button>
        <el-button type="primary" @click="confirmRichTextEdit">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { FeaturedContentProperty, FeaturedItem } from './config'
import { useVModel } from '@vueuse/core'
import { Editor } from '@/components/Editor'

defineOptions({ name: 'FeaturedContentProperty' })

const props = defineProps<{ modelValue: FeaturedContentProperty }>()
const emit = defineEmits(['update:modelValue'])

const formData = useVModel(props, 'modelValue', emit)

// 富文本弹窗相关状态
const richTextDialogVisible = ref(false)
const currentRichText = ref('')
const currentEditingIndex = ref(-1)

// 添加项目
const addItem = () => {
  const newId = Math.max(...formData.value.featuredItems.map(item => item.id), 0) + 1
  formData.value.featuredItems.push({
    id: newId,
    title: '',
    imgUrl: '',
    contentType: 'ad',
    price: '',
    url: ''
  })
}

// 内容类型变化处理
const onContentTypeChange = (index: number) => {
  const item = formData.value.featuredItems[index]
  if (item.contentType === 'text') {
    // 切换到文本类型，清空价格，设置默认富文本
    item.price = undefined
    if (!item.richText) {
      item.richText = ''
    }
  } else {
    // 切换到广告类型，清空富文本，设置默认价格
    item.richText = undefined
    if (!item.price) {
      item.price = ''
    }
  }
}

// 删除项目
const removeItem = (index: number) => {
  if (formData.value.featuredItems.length > 1) {
    formData.value.featuredItems.splice(index, 1)
  }
}

// 上移项目
const moveItemUp = (index: number) => {
  if (index > 0) {
    const items = formData.value.featuredItems
    const temp = items[index]
    items[index] = items[index - 1]
    items[index - 1] = temp
  }
}

// 下移项目
const moveItemDown = (index: number) => {
  const items = formData.value.featuredItems
  if (index < items.length - 1) {
    const temp = items[index]
    items[index] = items[index + 1]
    items[index + 1] = temp
  }
}

// 打开富文本编辑弹窗
const openRichTextDialog = (index: number) => {
  currentEditingIndex.value = index
  currentRichText.value = formData.value.featuredItems[index].richText || ''
  richTextDialogVisible.value = true
}

// 确认富文本编辑
const confirmRichTextEdit = () => {
  if (currentEditingIndex.value >= 0) {
    formData.value.featuredItems[currentEditingIndex.value].richText = currentRichText.value
  }
  richTextDialogVisible.value = false
  currentEditingIndex.value = -1
  currentRichText.value = ''
}

// 取消富文本编辑
const cancelRichTextEdit = () => {
  richTextDialogVisible.value = false
  currentEditingIndex.value = -1
  currentRichText.value = ''
}

// 弹窗关闭前处理
const handleRichTextDialogClose = () => {
  cancelRichTextEdit()
}

// 获取富文本预览内容
const getRichTextPreview = (richText: string) => {
  if (!richText) return ''
  // 移除HTML标签，只显示纯文本预览，限制长度
  const textContent = richText.replace(/<[^>]*>/g, '')
  return textContent.length > 50 ? textContent.substring(0, 50) + '...' : textContent
}
</script>

<style scoped lang="scss">
// 全局表单项标签样式
:deep(.el-form-item__label) {
  color: #333 !important;
  font-weight: 500;
}

// 全局输入框文字样式
:deep(.el-input__inner) {
  color: #333 !important;
}

:deep(.el-input__inner::placeholder) {
  color: #999 !important;
}

// 单选按钮组文字样式
:deep(.el-radio__label) {
  color: #333 !important;
}

// 数字输入框样式
:deep(.el-input-number__input) {
  color: #333 !important;
}

.compact-form {
  .el-form-item {
    margin-bottom: 12px;
    
    .el-form-item__label {
      color: #333 !important;
      font-weight: 500;
    }
  }
}

.section-header {
  margin-bottom: 8px !important;
  
  .section-title {
    font-size: 16px;
    font-weight: bold;
    color: #333;
    padding: 8px 0;
    border-bottom: 2px solid #409eff;
    margin-bottom: 8px;
  }
}

.config-card,
.items-config-card {
  margin-bottom: 12px;
  
  .config-section {
    margin-bottom: 16px;
    
    .section-label {
      font-size: 14px;
      font-weight: 600;
      color: #333;
      margin-bottom: 8px;
      padding: 4px 0;
      border-left: 3px solid #409eff;
      padding-left: 8px;
    }
  }
  
  .item-config {
    margin-bottom: 12px;
    padding: 8px;
    background: #f8f9fa;
    border-radius: 6px;
    
    .item-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 8px;
      
      .item-title {
        font-weight: bold;
        color: #333;
        font-size: 14px;
      }
      
      .item-actions {
        display: flex;
        gap: 4px;
        
        .el-button {
          padding: 4px 8px;
          font-size: 12px;
        }
      }
    }
  }
  
  .form-row {
    display: flex;
    gap: 8px;
    margin-bottom: 8px;
    
    .form-col {
      flex: 1;
      margin-bottom: 0;
    }
  }
  
  .compact-item {
    margin-bottom: 8px;
  }
  
  .full-width-item {
    margin-bottom: 12px;
    
    .el-form-item__content {
      width: 100%;
    }
    
    .el-form-item__label {
      color: #333 !important;
      font-weight: 500;
    }
  }
  
  .rich-text-button-container {
    .rich-text-preview {
      margin-top: 8px;
      padding: 8px 12px;
      background-color: #f5f7fa;
      border: 1px solid #e4e7ed;
      border-radius: 4px;
      font-size: 12px;
      color: #606266;
      line-height: 1.4;
      max-height: 60px;
      overflow: hidden;
    }
  }
}

// 富文本弹窗样式
.rich-text-dialog-content {
  padding: 0;
  
  :deep(.w-e-toolbar) {
    border-color: #dcdfe6;
  }
  
  :deep(.w-e-text-container) {
    border-color: #dcdfe6;
    border-top: none;
  }
  
  :deep(.w-e-text-placeholder) {
    color: #999;
  }
}

.dialog-footer {
  text-align: right;
}

// 响应式设计
@media (max-width: 768px) {
  .compact-form {
    .el-form-item__label {
      width: 60px !important;
      font-size: 12px;
      color: #333 !important;
      font-weight: 500;
    }
    
    .el-input__inner {
      color: #333 !important;
    }
    
    .el-radio__label {
      color: #333 !important;
    }
  }
  
  .config-card,
  .items-config-card {
    .form-row {
      flex-direction: column;
      gap: 4px;
      
      .form-col {
        width: 100%;
      }
    }
    
    .item-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 8px;
      
      .item-actions {
        width: 100%;
        justify-content: flex-end;
      }
    }
    
    .full-width-item {
      .el-form-item__label {
        width: 60px !important;
        font-size: 12px;
        color: #333 !important;
        font-weight: 500;
      }
    }
  }
}

@media (max-width: 480px) {
  .compact-form {
    .el-form-item__label {
      width: 50px !important;
      color: #333 !important;
      font-weight: 500;
    }
    
    .el-input__inner {
      color: #333 !important;
    }
    
    .el-radio__label {
      color: #333 !important;
    }
  }
  
  .config-card,
  .items-config-card {
    .item-config {
      padding: 6px;
    }
    
    .item-actions {
      .el-button {
        padding: 2px 6px;
        font-size: 11px;
      }
    }
    
    .full-width-item {
      .el-form-item__label {
        width: 50px !important;
        font-size: 11px;
        color: #333 !important;
        font-weight: 500;
      }
    }
  }
}
</style>